package cn.com.anysdk.demo.service.Impl;

import cn.com.anysdk.demo.service.IOssService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import cn.com.anysdk.demo.common.Response;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Service
public class AliyunIOssService implements IOssService {

    @Resource
    private OSS ossClient;

    @Value("${anysdk.oss.aliyun.bucket-name}")
    private String bucketName;

    @Value("${anysdk.oss.aliyun.endpoint}")
    private String endPoint;

    @Override
    public Response<String> upload(MultipartFile file) {
        try {
            if (file == null || file.isEmpty()) {
                return Response.fail(Response.BAD_REQUEST, "上传文件不能为空");
            }

            // 获取原文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return Response.fail(Response.BAD_REQUEST, "文件名不能为空");
            }

            // 生成新的唯一的文件名并保留后缀
            String fileName = UUID.randomUUID().toString() + "." +
                    originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            // 设置文件元信息
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(file.getContentType());
            metadata.setContentLength(file.getSize());

            // 上传文件
            ossClient.putObject(bucketName, fileName, file.getInputStream(), metadata);

            // 生成文件访问URL（默认私有，需要签名）
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000); // 1小时有效期
            URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);

            return Response.success("文件上传成功", url.toString());
        } catch (IOException e) {
            return Response.fail(Response.INTERNAL_ERROR, "文件上传失败：" + e.getMessage());
        } catch (OSSException e) {
            return Response.fail(Response.INTERNAL_ERROR, "OSS服务异常：" + e.getMessage());
        }
    }

    @Override
    public Response<byte[]> download(String fileName) {
        try {
            if (!ossClient.doesObjectExist(bucketName, fileName)) {
                return Response.fail(Response.NOT_FOUND, "文件不存在");
            }

            // 获取文件对象
            OSSObject ossObject = ossClient.getObject(bucketName, fileName);

            // 读取文件内容
            try (InputStream inputStream = ossObject.getObjectContent();
                 ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                return Response.success("文件下载成功", outputStream.toByteArray());
            }
        } catch (OSSException e) {
            return Response.fail(Response.INTERNAL_ERROR, "OSS服务异常：" + e.getMessage());
        } catch (IOException e) {
            return Response.fail(Response.INTERNAL_ERROR, "文件读取失败：" + e.getMessage());
        }
    }

    @Override
    public Response<String> delete(String fileName) {
        try {
            if (fileName == null || fileName.trim().isEmpty()) {
                return Response.fail(Response.BAD_REQUEST, "文件名不能为空");
            }

            // 检查文件是否存在
            if (!ossClient.doesObjectExist(bucketName, fileName)) {
                return Response.fail(Response.NOT_FOUND, "文件不存在");
            }

            // 删除文件
            ossClient.deleteObject(bucketName, fileName);
            return Response.success("文件删除成功");
        } catch (OSSException e) {
            return Response.fail(Response.INTERNAL_ERROR, "OSS服务异常：" + e.getMessage());
        }
    }

    /**
     * 生成文件访问URL
     * @param fileName 文件名
     * @param expireTime URL过期时间（秒）
     * @return 访问URL
     */
    public String generatePresignedUrl(String fileName, Long expireTime) {
        try {
            if (fileName == null || fileName.trim().isEmpty()) {
                throw new IllegalArgumentException("文件名不能为空");
            }

            if (expireTime == null || expireTime <= 0) {
                expireTime = 3600L; // 默认1小时
            }

            Date expiration = new Date(System.currentTimeMillis() + (expireTime * 1000));
            URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
            return url.toString();
        } catch (Exception e) {
            throw new RuntimeException("生成文件访问URL失败：" + e.getMessage());
        }
    }

    /**
     * 检查文件是否存在
     * @param fileName 文件名
     * @return 是否存在
     */
    public boolean doesObjectExist(String fileName) {
        return ossClient.doesObjectExist(bucketName, fileName);
    }
}
